package com.lyj.controller;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lyj.pojo.DeptInfo;
import com.lyj.pojo.EducationInfo;
import com.lyj.pojo.User;
import com.lyj.service.EchartsDataService;
import com.lyj.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class WelcomeController {
    @Autowired
    private EchartsDataService echartsDataService;

    @Autowired
    private UserService userService;

    @RequestMapping("/toWelcome")
    public ModelAndView toWelcome(ModelAndView mv){
        List<EducationInfo> educationInfos = echartsDataService.getEducationInfo();
        List<DeptInfo> deptInfos = echartsDataService.getDeptInfo();
//        educationInfos.forEach(e -> System.out.println(e));
        mv.addObject("educationInfo", JSONUtil.toJsonStr(educationInfos));
        mv.addObject("deptInfo", JSONUtil.toJsonStr(deptInfos));
        mv.setViewName("welcome");
        return mv;
    }

    @RequestMapping("/toLogin")
    public String toLogin(HttpServletRequest request, HttpSession session){
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            System.out.println("检查到了cookie");
            for (Cookie cookie : cookies) {
                if ("user".equals(cookie.getName())){
                    System.out.println("检查到了上次登录的用户");
                    String value = cookie.getValue();
                    try {
                        value = URLDecoder.decode(value, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    JSONObject entries = JSONUtil.parseObj(value);
                    String loginName = (String) entries.get("loginName");
                    String password = (String) entries.get("password");
//                    System.out.println("登录名：" + loginName);
                    User login = userService.login(loginName, password);
                    if (login != null){
                        session.setAttribute("loginUser",login);
                        return "redirect:/user/toHome";
                    }

                }
            }
        }
        return "login";
    }
    @RequestMapping("/toRegister")
    public ModelAndView toRegister(ModelAndView mv){
        mv.setViewName("register");
        return mv;
    }


}
